package com.xiaodeng.edu.interceptors;

import com.xiaodeng.edu.utils.JwtUtil;
import com.xiaodeng.edu.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Target(ElementType.METHOD)
    @Retention(RetentionPolicy.RUNTIME)
    public @interface GlobalJwtIntercept {
    }
  @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
      HandlerMethod handlerMethod = (HandlerMethod) handler;
      GlobalJwtIntercept loginIntercept = handlerMethod.getMethod().getAnnotation(GlobalJwtIntercept.class);
      //如果要访问的方法上没有加这个注解，那么就说明这个方法不需要拦截，否则就需要进行拦截
        if (null == loginIntercept) return true;
        
        //令牌验证
        String token = request.getHeader("Authorization");
        //验证token
        try {

            Map<String, Object> claims = JwtUtil.parseToken(token);
            //把业务数据存储到ThreadLocal中
            ThreadLocalUtil.set(claims);
            //放行
            return true;

        } catch (Exception e) {
            //http响应码为401
            response.setStatus(401);
            return false;
        }

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //清空ThrradLocalh中的数据
      ThreadLocalUtil.remove();
    }
}
